package com.example.demo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.demo.entity.*;
import com.example.demo.service.AdminService;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@AllArgsConstructor
public class AdminController {

    private final AdminService adminService;

    // 用户管理
    @GetMapping("/users")
    public ResponseEntity<IPage<User>> getUsers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int size,
            @RequestParam(required = false) String keyword) {
        return ResponseEntity.ok(adminService.getUserPage(page, size, keyword));
    }

    @DeleteMapping("/users/{id}")
    public ResponseEntity<Boolean> deleteUser(@PathVariable Integer id) {
        return ResponseEntity.ok(adminService.deleteUser(id));
    }

    @GetMapping("/users/{id}")
    public ResponseEntity<Map<String, Object>> getUserDetails(@PathVariable Integer id) {
        try {
            User user = adminService.getUserDetails(id);
            if (user == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Map.of(
                                "status", "error",
                                "message", "用户不存在",
                                "id", id
                        ));
            }

            // 使用实体类定义的JsonProperty名称
            Map<String, Object> response = new HashMap<>();
            response.put("uId", user.getUId());
            response.put("uName", user.getUName());
            response.put("uPhoneNumber", user.getUPhoneNumber());
            response.put("uBio", user.getUBio());
            response.put("uIsAdmin", user.getUIsAdmin());
            response.put("uBalance", user.getUBalance());

            return ResponseEntity.ok(Map.of("data", response));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of(
                            "status", "error",
                            "message", "获取用户详情失败: " + e.getMessage()
                    ));
        }
    }

    // 商品管理
    @GetMapping("/goods")
    public ResponseEntity<IPage<Goods>> getGoods(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int size,
            @RequestParam(required = false) String keyword) {
        // 处理空keyword
        if(keyword != null && keyword.trim().isEmpty()) {
            keyword = null;
        }

        return ResponseEntity.ok(adminService.getGoodsPage(page, size, keyword));
    }

    @DeleteMapping("/goods/{id}")
    public ResponseEntity<Boolean> deleteGoods(@PathVariable Integer id) {
        return ResponseEntity.ok(adminService.deleteGoods(id));
    }

    @GetMapping("/goods/{id}")
    public ResponseEntity<Map<String, Object>> getGoodsDetails(@PathVariable Integer id) {
        try {
            Goods goods = adminService.getGoodsDetails(id);
            if (goods == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Map.of(
                                "status", "error",
                                "message", "商品不存在",
                                "id", id
                        ));
            }

            Map<String, Object> response = new HashMap<>();
            response.put("gId", goods.getGId());
            response.put("gName", goods.getGName());
            response.put("gPrice", goods.getGPrice());
            response.put("gStockQuantity", goods.getGStockQuantity());
            response.put("gCategory", goods.getGCategory());
            response.put("gUserId", goods.getGUserId());
            response.put("gIsActive", goods.getGIsActive());
            response.put("gIsTrade", goods.getGIsTrade());
            response.put("gDescription", goods.getGDescription());
            response.put("gCreateTime", goods.getGCreateTime());

            return ResponseEntity.ok(Map.of("data", response));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of(
                            "status", "error",
                            "message", "获取商品详情失败: " + e.getMessage()
                    ));
        }
    }

    // 订单管理
    @GetMapping("/orders")
    public ResponseEntity<IPage<OrdersManagement>> getOrders(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int size,
            @RequestParam(required = false) String keyword) {
        return ResponseEntity.ok(adminService.getOrdersPage(page, size, keyword));
    }

    @DeleteMapping("/orders/{id}")
    public ResponseEntity<Boolean> deleteOrder(@PathVariable Integer id) {
        return ResponseEntity.ok(adminService.deleteOrder(id));
    }

    @GetMapping("/orders/{id}")
    public ResponseEntity<Map<String, Object>> getOrderDetails(@PathVariable Integer id) {
        try {
            OrdersManagement order = adminService.getOrderDetails(id);
            if (order == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Map.of(
                                "status", "error",
                                "message", "订单不存在",
                                "id", id
                        ));
            }

            Map<String, Object> response = new HashMap<>();
            response.put("oId", order.getOId());
            response.put("oGoodsId", order.getOGoodsId());
            response.put("oUserIdOne", order.getOUserIdOne());
            response.put("oUserIdTwo", order.getOUserIdTwo());
            response.put("oTotalAmount", order.getOTotalAmount());
            response.put("oStatus", order.getOStatus());
            response.put("oCreateTime", order.getOCreateTime());

            return ResponseEntity.ok(Map.of("data", response));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of(
                            "status", "error",
                            "message", "获取订单详情失败: " + e.getMessage()
                    ));
        }
    }


    // 评论管理
    @GetMapping("/comments")
    public ResponseEntity<IPage<Comments>> getComments(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int size,
            @RequestParam(required = false) String keyword) {
        return ResponseEntity.ok(adminService.getCommentsPage(page, size, keyword));
    }

    @DeleteMapping("/comments/{id}")
    public ResponseEntity<Boolean> deleteComment(@PathVariable Integer id) {
        return ResponseEntity.ok(adminService.deleteComment(id));
    }

    @GetMapping("/comments/{id}")
    public ResponseEntity<Map<String, Object>> getCommentDetails(@PathVariable Integer id) {
        try {
            Comments comment = adminService.getCommentDetails(id);
            if (comment == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Map.of(
                                "status", "error",
                                "message", "评论不存在",
                                "id", id
                        ));
            }

            Map<String, Object> response = new HashMap<>();
            response.put("cId", comment.getCId());
            response.put("cUserId", comment.getCUserId());
            response.put("cGoodsId", comment.getCGoodsId());
            response.put("cBio", comment.getCBio());

            return ResponseEntity.ok(Map.of("data", response));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of(
                            "status", "error",
                            "message", "获取评论详情失败: " + e.getMessage()
                    ));
        }
    }

    // 个人管理
    @PutMapping("/profile/bio")
    public ResponseEntity<Boolean> updateBio(
            @RequestParam Integer userId,
            @RequestParam String bio) {
        return ResponseEntity.ok(adminService.updateUserBio(userId, bio));
    }

    @PutMapping("/profile/password")
    public ResponseEntity<Boolean> changePassword(
            @RequestParam Integer userId,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {
        return ResponseEntity.ok(adminService.changePassword(userId, oldPassword, newPassword));
    }

    @PostMapping("/profile/recharge")
    public ResponseEntity<BigDecimal> rechargeBalance(
            @RequestParam Integer userId,
            @RequestParam BigDecimal amount) {
        return ResponseEntity.ok(adminService.rechargeBalance(userId, amount));
    }
}